import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android/model/search/search_page_model.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final RefreshController _refreshController = RefreshController();
  final TextEditingController _controllerField = TextEditingController();
  late FocusNode _focusNode;

  bool isShowList = false;

  SearchPageModel? _searchPageModel = null;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          isShowList = false;
        });
      } else {
        isShowList = true;
      }
    });

    final SearchPageModel searchPageModel = Provider.of<SearchPageModel>(context, listen: false);
    searchPageModel.getHotList();

    setState(() {
      _searchPageModel = searchPageModel;
    });
  }

  @override
  void dispose() {
    _controllerField.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  List<Widget> _recommendKeys() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('搜索热词', style: TextStyle(fontSize: 28.sp)),
          TextButton(
            child: Row(
              children: [
                const Icon(Icons.refresh_outlined, size: 16),
                Text('换一换', style: TextStyle(fontSize: 28.sp))
              ],
            ),
            onPressed: () {
              print('换一换');
            },
            // onPressed: onPressed, child: child
          )
        ],
      ),

      Align(
        alignment: Alignment.centerLeft,
        child: Consumer<SearchPageModel>(builder: (context, vm, child) {

          return Wrap(
            // spacing: 20.r,
            runSpacing: 20.r,
            crossAxisAlignment: WrapCrossAlignment.center,
            children: vm.hotList.map((item) {
              return Padding(
                padding: EdgeInsets.only(bottom: 10.r, right: 10.r),
                child: ElevatedButton(
                  child: Text(item.name),
                  onPressed: () {
                    _controllerField.text = item.name;

                    vm.getSearchList({'k': _controllerField.text});
                    setState(() {
                      isShowList = true;
                    });
                  },
                )
              );
            }).toList()
          );
        })
      ),
    ];
  }

  AppBar _appBar() {
    return AppBar(
      leadingWidth: 60.w,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new_outlined),
        onPressed: () {
          context.pop();
        },
      ),
      backgroundColor: Colors.grey[100],
      title: TextField(
        controller: _controllerField,
        focusNode: _focusNode,
        decoration: InputDecoration(
          // labelText: '输入文本',
          focusedBorder: const UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black54)
          ),
          hintText: '搜索',
          hintStyle: TextStyle(color: Colors.black54, fontSize: 28.sp),
          border: const UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.white70)
          ),
          prefixIcon: const Icon(Icons.search, color: Colors.black26,),
        ),
        style: TextStyle(color: Colors.black, fontSize: 40.sp),
      ),
      actions: [
        InkWell(
          child: const Icon(Icons.close_outlined),
          onTap: () {
            if (_controllerField.text.isEmpty) {
              context.pop();
              return;
            }
            _controllerField.text = '';
          },
        )
      ],
    );
  }

  Widget _hotKeyWidget() {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 20.h),
        child: Column(
          children: <Widget>[
            ..._recommendKeys(),
          ],
        ),
      )
    );
  }

  Widget _searchListWidget() {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: const ClassicHeader(),
      footer: const ClassicFooter(),
      onRefresh: () async {
        await _searchPageModel!.getSearchList({'k': _controllerField.text}, loadMore: false);
        _refreshController.refreshCompleted();
      },
      onLoading: () async {
        await _searchPageModel!.getSearchList({'k': _controllerField.text}, loadMore: true);
        _refreshController.loadComplete();
      },
      child: SingleChildScrollView(
        child:  Consumer<SearchPageModel>(
          builder: (context, vm, child) {
            return ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: vm.searchList.length,
              itemBuilder: (BuildContext context, int index) {
                DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(vm.searchList[index].shareDate);
                String date = '${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}:${dateTime.second}';

                return InkWell(
                  onTap: () {
                    // context.push('/webview?url=${vm.searchList[index].link}}');
                    context.push('/webview?url=${vm.searchList[index].link}');
                  },
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 40.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                const Icon(Icons.person),
                                Text(vm.searchList[index].author.isEmpty ? 'One' : vm.searchList[index].author),
                              ],
                            ),
                            Text(date, style: const TextStyle(fontWeight: FontWeight.bold),)
                          ]
                        ),
                        
                        Padding(
                          padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                          // child: Text(vm.searchList[index].title),
                          child: Html(data: vm.searchList[index].title.isEmpty ? '--' : vm.searchList[index].title),
                        ),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text(vm.searchList[index].superChapterName.toString()),
                                Icon(Icons.circle, size: 10.sp,),
                                Text(vm.searchList[index].chapterName),
                              ],
                            ),
                            const Icon(Icons.favorite_border, color: Colors.redAccent,)
                          ],
                        )
                      ],
                    ),
                  ),
                );
              }
            );
          },
        )
      ),
    );
  }

  // 内容区域：列表 / 热词
  Widget _body() {
    if (isShowList) {
      return _searchListWidget();
    }
    
    return _hotKeyWidget();
  }

  @override
  Widget build(BuildContext context) {

    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: _appBar(),

        body: _body()
      ),
    );
  }
}